package com.hymjweb.demo.hymj.basic_data_manage.xt_upload_file.service;

import com.github.pagehelper.PageInfo;
import com.hymjweb.demo.framework.result.MIniUIGridResultMap;
import com.hymjweb.demo.framework.sys.BaseService;
import com.hymjweb.demo.framework.sys.SysConstant;
import com.hymjweb.demo.framework.util.DataTypeUtil;
import com.hymjweb.demo.hymj.basic_data_manage.xt_upload_file.bean.XtUploadFilePojo;
import com.hymjweb.demo.hymj.basic_data_manage.xt_upload_file.mapper.XtUploadFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class XtUploadFileService extends BaseService {


    @Autowired
    private XtUploadFileMapper xtUploadFileMapper;

    @Value(value = "${my.tempFilePath}")
    private String myTempFilePath;

    public Object getPageList(Map map) {

        // 分页初始化
        this.pageListInit(map);

        // 获取查询列表
        List list = xtUploadFileMapper.findAll(map);;

        // 封装到PageInfo对象中
        PageInfo pageInfo = new PageInfo(list);

        MIniUIGridResultMap resultMap = new MIniUIGridResultMap(pageInfo);

        return resultMap;
    }

    public XtUploadFilePojo findObjectById(String id){
        return xtUploadFileMapper.findObjectById(id);
    }


    @Transactional(rollbackFor = {Exception.class})
    public int delete(Map param) {

        int flag = SysConstant.OPERATE_STATUS.SUCCESS.getId();

        String id = DataTypeUtil.toStringObject(param.get("id"));

        if(id == null){
            flag = SysConstant.OPERATE_STATUS.EXCEPTION_ID.getId();
        }
        else{
            // 根据id获取要删除的对象
            XtUploadFilePojo pojo = xtUploadFileMapper.findObjectById(id);
            deleteFile(pojo);
        }
        return  flag;
    }


    /**
     * 上传文件到指定的目录，并向数据库中写入文件对象记录
     * @param upLoadFile
     * @return
     * @throws Exception
     */
    public XtUploadFilePojo upload(MultipartFile upLoadFile) throws Exception {

        String fileName = upLoadFile.getOriginalFilename();
        // 获取扩展名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 获取放入指定的文件路径
        String path = this.myTempFilePath;

        File parentDir = new File(path);

        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        String saveFileName = this.getSysStrId() + suffixName;

        File destFile = new File(parentDir, saveFileName);

        try {
            // 上传的文件写入到目标文件中
            upLoadFile.transferTo(destFile);

        } catch (Exception e) {
            throwException("文件上传失败!");
        }

        Date currentDate = this.getSysTime();
        String czyId = this.getLoginCzyId();
        // 上传完成后进行记录写入数据库
        XtUploadFilePojo pojo = new XtUploadFilePojo();
        pojo.setId(this.getSysStrId());
        pojo.setFileTitle(fileName);
        pojo.setFileName(destFile.getName());
        pojo.setCreateTime(currentDate);
        pojo.setCreateUserId(czyId);
        pojo.setUpdateTime(currentDate);
        pojo.setUpdateUserId(czyId);

        int effectRow = xtUploadFileMapper.insert(pojo);

        if(effectRow == 0){
            destFile.delete();
            return  null;
        }
        return pojo;
    }


    public File getFile(XtUploadFilePojo pojo) {
        File file = getFile(pojo.getFileName());
        if(file!=null){
            return file;
        }
        return null;
    }

    public File getFile(String  fileNmae) {
        if(fileNmae!=null){
            return new File(myTempFilePath,fileNmae);
        }
        return null;
    }


    @Transactional(rollbackFor = {Exception.class})
    public void deleteFile(List<String> fileIds){
        if(fileIds!=null && fileIds.size()>0){
            for(String fileId:fileIds){
                XtUploadFilePojo pojo = xtUploadFileMapper.findObjectById(fileId);
                if(pojo!=null){
                    deleteFile(pojo);
                }
            }
        }
    }

    @Transactional(rollbackFor = {Exception.class})
    public void deleteFile(XtUploadFilePojo filePojo){
        if(filePojo!=null){
            File file = getFile(filePojo);
            if(file!=null){
                // 1.先删除文件对象
                Map<String,Object> map = new HashMap<>();
                map.put("id",filePojo.getId());
                xtUploadFileMapper.delete(map);
                // 2.删除文件
                deleteFile(file);
            }
        }
    }

    public void deleteFile(File file) {
        if(file!=null && file.exists()){
            file.delete();
        }
    }
}

